package com.iw.sms.quartz;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alvin.sms.model.SendSmsVO;
import com.iw.point.service.SmsPointServer;
import com.iw.sms.entity.Sms;
import com.iw.sms.entity.SmsState;
import com.iw.sms.entity.SmsType;
import com.iw.sms.service.AlvinSmsService;
import com.iw.sms.service.SmsService;

@Component
public class AutoReplyQuartz {

	public static boolean isRun = false;
	public static Long waitTime = 1 * 100L;

	static {
		isRun = SmsConfig.getRun(SmsConfig.AUTO_REPLY_RUN);
	}

	@Autowired
	private SmsService smsService;

	@Autowired
	private AlvinSmsService alvinSmsService;

	public void run() {
		if (isRun) {
			try {
				if (AlvinSmsService.isRun) { // 短信功能可用的时候才执行下面的
					String hql = "from Sms where type = ? and state = ?";

					List<Sms> list = smsService.findList(hql, SmsType.R, SmsState.WIL_REPLY);

					for (Sms sms : list) {
						SmsPointServer smsPointServer = new SmsPointServer(smsService.getBaseDao().getNewSession());
						HashMap<String, String> msgMap = smsPointServer.doPoints(sms); // 开始积分
						String content = "";
						Iterator<String> keys = msgMap.keySet().iterator();
						while (keys.hasNext()) {
							String key = keys.next();
							content = key + msgMap.get(key) + content;
						}
						SendSmsVO vo = new SendSmsVO(sms.getMobile(), content);
						boolean flag = alvinSmsService.sendSms(vo);
						if (flag) {
							sms.setState(SmsState.HAD_REPLY);
						} else {
							sms.setState(SmsState.HAD_DONE);
						}
						Thread.sleep(waitTime);
						smsService.update(sms);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
